package cn.mengfly.testnrz.nio;

import cn.mengfly.testnrz.util.IOUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelCopy {


    public static void nioCopyResourceFile() {
        String sourcePath = NioDemoConfig.getPath(NioDemoConfig.FILE_TEST);
        String destPath = NioDemoConfig.getPath("copy.txt");

        File srcFile = new File(sourcePath);
        File destFile = new File(destPath);

        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel inChannel = null;
        FileChannel outChannel = null;

        try {
            if (!destFile.exists()) {
                if (!destFile.createNewFile()) {
                    System.out.println("无法创建copy文件");
                    return;
                }
            }
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);
            inChannel = fis.getChannel();
            outChannel = fos.getChannel();

            ByteBuffer buf = ByteBuffer.allocate(1024);
            while (inChannel.read(buf) != -1) {
                buf.flip();
                int outLength;
                while ((outLength = outChannel.write(buf)) != 0) {
                    System.out.println("写入字节数:" + outLength);
                }
                buf.clear();
            }
            outChannel.force(true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtil.close(outChannel, inChannel, fos, fis);
        }

    }

    public static void main(String[] args) {
        nioCopyResourceFile();
    }
}
